﻿using System;
using System.Windows.Forms;

namespace AnalysisMsg
{

    public partial class Output : Form
    {

        public static bool CurrInputDataTypeValidFlag = false;  //  判断当前输入的数据是否符合规范

        public static byte[] inputdata_hex = new byte[1000];
        public static byte[] MsgDI = new byte[4];

        public static string sTmp;  //临时使用的string 变量

        TreeNode node = new TreeNode();
        TreeNodeTag Ttag = new TreeNodeTag();

        public Output()
        {
            InitializeComponent();
        }


        public static byte BYTE2BCD(byte Value)
        {
            return (byte)((byte)((Value / 10) << 4) | (Value % 10));
        }

        public static byte BCD2BYTE(byte Value)
        {
            return (byte)((Value >> 4) * 10 + (Value & 0x0F));
        }

        public static ushort WORD2BCD(ushort Value)
        {
            return (ushort)((BYTE2BCD((byte)(Value / 100)) << 8) | (BYTE2BCD((byte)(Value % 100))));
        }

        public static ushort BCD2WORD(ushort Value)
        {
            return (ushort)((ushort)BCD2BYTE((byte)(Value >> 8)) * 100 + BCD2BYTE((byte)(Value & 0xFF)));
        }

        public static ulong DWORD2BCD(ulong Value)
        {
            return (ulong)((WORD2BCD((ushort)(Value / 10000)) << 16) | (WORD2BCD((ushort)(Value % 10000))));
        }

        public static ulong BCD2DWORD(ulong Value)
        {
            return (ulong)(BCD2WORD((ushort)(Value >> 16)) * 10000 + BCD2WORD((ushort)(Value & 0xFFFF)));
        }


        /// <summary>
        /// 计算数组加和
        /// </summary>
        /// <param name="bArr"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static byte CheckSum(byte[] bArr, int length)
        {
            long tmp = 0;

            for (int i = 0; i < length - 2; i++)
            {
                tmp += bArr[i];
            }

            return (byte)(tmp);

        }



        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";//空格
                         //throw new ArgumentException("s is not valid chinese string!");
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }

        ///<summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。
            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                                          System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message.
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }


        /// <summary>
        /// 输入的字符串转成byte 数组
        /// </summary>
        /// <param name="indata"></param>
        /// <returns></returns>
        public static byte[] StringToHexByte(string indata)
        {
            int i = 0;
            //bool j = false;

            char[] chs = { ' ' };
            string[] res = indata.Split(chs, options: StringSplitOptions.RemoveEmptyEntries);

            byte[] tempresult = new byte[res.Length];

            foreach (var item in res)
            {
                //Console.WriteLine(item);
                try
                {
                    tempresult[i] = byte.Parse(res[i], System.Globalization.NumberStyles.HexNumber);

                    CurrInputDataTypeValidFlag = true;
                }
                catch (System.AccessViolationException)
                {
                    Array.Clear(res, 0, res.Length);
                }
                catch (System.InvalidCastException)
                {
                    Array.Clear(res, 0, res.Length);
                    MessageBox.Show("输入格式异常");
                }
                catch (System.NullReferenceException)
                {
                    Array.Clear(res, 0, res.Length);
                    MessageBox.Show("输入格式异常1");
                }
                catch (System.ArgumentNullException)
                {// 字符串为 空
                    Array.Clear(res, 0, res.Length);
                    MessageBox.Show("输入格式异常2");
                }
                catch (System.FormatException)
                {// 输入 非 数字字符
                    Array.Clear(res, 0, res.Length);
                    MessageBox.Show("输入格式异常3");
                    CurrInputDataTypeValidFlag = false;
                }
                catch (System.OverflowException)
                {///超出 类型范围 
                    Array.Clear(res, 0, res.Length);
                    MessageBox.Show("输入格式异常4");
                }

                i++;
            }

            return tempresult;
        }


        byte[] tmpdata = new byte[12];
        private void btn_Send_Click(object sender, EventArgs e)
        {
            if (txt_MeterID.Text == null)
            {
                MessageBox.Show("请输入表号： ！！！");
                txt_MeterID.Text = null;
                return;
            }

            if (this.txt_MeterID.Text.Length != 12)
            {
                MessageBox.Show("输入表号：异常 ！！！");
                txt_MeterID.Text = null;
                return;
            }
            else
            {
                //tmpdata = inputID.ToCharArray(0, this.txt_MeterID.Text.Length);
                tmpdata = strToToHexByte(this.txt_MeterID.Text);
            }


            // 写表号信息：
            sTmp = "68 ";
            for (int i = 5; i > 0; i--)
            {
                sTmp += tmpdata[i].ToString("X2");
                sTmp += " ";
            }
            sTmp += "68";
            //表号信息结束 


            /// 判断选中树的父节点
            switch (LastParentName)
            {
                case "ReadData":
                    sTmp += " 11 04";
                    break;

                case "":
                    sTmp += "";
                    break;

                default:
                    break;
            }

            //// 判断树选中项
            switch (TreeViewSelectName)
            {
                case "TotalPositiveActiveEnergy":
                    sTmp += " 00 00 01 00 ";
                    break;

                default:
                    break;
            }




            txt_items.Text = TreeViewSelectVal + TreeViewSelectName;
            txt_OutPutMsg.Text = sTmp;
        }

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        string TreeViewSelectVal = null;
        string TreeViewSelectName = null;
        string FirstTierName = null;
        string SecondTierName = null;
        string ThirdTierName = null;
        string LastParentName = null;

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeViewSelectVal = e.Node.Text;
            TreeViewSelectName = e.Node.Name;

            if (e.Node.Level != 0)
            {
                TreeNode selNode = treeView1.SelectedNode;
                if (selNode == null)
                {
                    //防止空引用bai
                    return;
                }
                if (selNode.Parent != null)
                {
                    //为有父亲节点du的,
                    TreeNode parentNode = selNode.Parent;//得到父亲节点

                    for (int i = 0; i < parentNode.Level; i++)
                    {
                        switch (i)
                        {
                            case 0:
                                FirstTierName = parentNode.Name;
                                break;
                            case 1:
                                SecondTierName = parentNode.Name;
                                break;
                            case 2:
                                ThirdTierName = parentNode.Name;
                                break;
                        }
                        parentNode = parentNode.Parent;//得到父亲节点
                        //i++;
                    }

                    LastParentName = parentNode.Name;
                }
            }
        }
    }


    public class TreeNodeTag
    {
        public string ID;//当前ID值
        public string LB;//类别
        public string parentID;//父节点ID
        public int js;//级数
        public string zf;//是否作废
    }
}
